//
//  CubeModuleUnZip.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-3.
//
//

#import "CubeModuleUnZip.h"
#import "IsolatedStorageFile(CubeLogic).h"
#import "SSZipArchive.h"
#import "CubesModel.h"

@interface CubeModuleUnZip()

-(void) failed;

-(void) success;

-(void)runUnZip;

-(void)runUnZipFinish:(NSNumber*)success;
@end

@implementation CubeModuleUnZip

- (void)dealloc{
    NSLog(@"CubeModuleUnZip dealloc");
}


-(void)cancel{
    running=NO;
    [thread cancel];
    thread=nil;
}

-(void)start{
    [self cancel];
    running=YES;
    NSString* filePath=[IsolatedStorageFile cubeModelTempZip:self.cubeModel.identifier];

    if([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:NO]){
        thread = [[NSThread alloc] initWithTarget:self selector:@selector(runUnZip) object:nil];
        [thread start];

    }
    else{
        [self failed];
    }
}


-(void) failed{
    [self.callback failed];
}

-(void) success{
    [self.callback success];
    
}

-(void)runUnZip{
    @autoreleasepool {

        NSString* filePath=[IsolatedStorageFile cubeModelTempZip:self.cubeModel.identifier];

        NSString* wwwPath = [IsolatedStorageFile cubeModuleIdentifierRoot:self.cubeModel.identifier];
    
        BOOL zipSuccess=[SSZipArchive unzipFileAtPath:filePath
                                   toDestination:wwwPath
                                       overwrite:YES password:nil error:nil];
        
        
        [self performSelectorOnMainThread:@selector(runUnZipFinish:) withObject:[NSNumber numberWithBool:zipSuccess] waitUntilDone:NO];
    }

}

-(void)runUnZipFinish:(NSNumber*)success{
    if(running){
        if([success boolValue]){
            [self success];
        }
        else{
            [self failed];
        }
    }
    
}


@end
